package com.lj.infoisland.handler;

import com.lj.infoisland.domain.vo.UserInfoVO;
import com.lj.infoisland.service.UsersService;
import com.lj.infoisland.util.UserContext;

import com.sun.istack.NotNull;
import lombok.AllArgsConstructor;
import org.springframework.web.servlet.HandlerInterceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.lj.infoisland.util.JwtUtil.extractUserIdFromToken;


@AllArgsConstructor
public class TokenInterceptor implements HandlerInterceptor {

    private UsersService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
        // 从请求头中获取token
        String token = request.getHeader("Token");

        // 提取token中的userId
        String userUniqueId = extractUserIdFromToken(token);

        // 查询数据库获取用户信息
        UserInfoVO user = userService.getUserInfo(userUniqueId).getData();

        // 将用户信息存储到ThreadLocal中
        UserContext.setUser(user);

        return true;
    }

    @Override
    public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, Exception ex) throws Exception {
        // 请求完成后，从ThreadLocal中移除用户信息
        UserContext.removeUser();
    }
}